package transientTables;

import java.sql.SQLException;

import rainbownlp.util.StringUtil;


public class TermsTFIDF {
	public static DBLayer db = new DBLayer();
	public static boolean insertTerm(String filename, 
			String term_text, double tfidf,
			int term_f, int doc_f) throws SQLException {
		
		term_text = StringUtil.prepareSQLString(term_text);
		String selectQuery = "select count(*) from TermsTFIDF where filename = '"
				+ filename + "' AND term_text='" +
						term_text+"';";
		
		int count = db.executeOneIntegerQuery(selectQuery);
		boolean added = false;
		if (count == 0) {
			String insertQuery = "insert into TermsTFIDF (filename, term_text, " +
					"tfidf, term_frequency, doc_frequency) values ('"
					+ filename + "','" +
						term_text + "'," +
						tfidf+"," +
						term_f+"," +
						doc_f+");";
			db.executeNonQuery(insertQuery);
			added = true;
		}
		return added;
	}
	
	public static void updateTFIDF(String filename, 
			String term_text, double tfidf) throws SQLException {
		
		term_text = StringUtil.prepareSQLString(term_text);
		String updateQ = "UPDATE TermsTFIDF SET tfidf = " +
				tfidf +" where filename = '"
				+ filename + "' AND term_text='" +
						term_text+"';";
		
		db.executeNonQuery(updateQ);
		
	}
	
	
	public static int getMaxTermFreq(String filename) throws SQLException {
		String selectQuery = "select max(term_frequency) from TermsTFIDF where filename = '"
			+ filename + "';";
		int maxTermFreq = db.executeOneIntegerQuery(selectQuery);
		return maxTermFreq;
	}
	public static double getTermTFIDF(String filename, String word) throws SQLException {
		word = StringUtil.prepareSQLString(word);
		String selectQuery = "select tfidf from TermsTFIDF where filename = '"
			+ filename + "' AND term_text='" +
			word+"';";
		double tfidf = db.executeOneDoubleQuery(selectQuery);
		if(tfidf==-1) tfidf = 0;
		return tfidf;
	}
}
